<template>
  <div class="applications-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">应用管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateDialog = true">
              <el-icon><Plus /></el-icon>
              创建应用
            </el-button>
            <el-button @click="showAIDialog = true">
              <el-icon><MagicStick /></el-icon>
              AI创建
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="应用名称">
          <el-input v-model="searchForm.name" placeholder="请输入应用名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="开发中" value="development" />
            <el-option label="已发布" value="published" />
            <el-option label="已停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 应用列表 -->
      <el-row :gutter="20">
        <el-col :span="6" v-for="app in applications" :key="app.id">
          <el-card class="app-card" shadow="hover">
            <div class="app-icon">
              <el-icon><component :is="app.icon" /></el-icon>
            </div>
            <div class="app-info">
              <h3>{{ app.name }}</h3>
              <p class="app-desc">{{ app.description }}</p>
              <div class="app-meta">
                <el-tag :type="getStatusType(app.status)" size="small">
                  {{ getStatusLabel(app.status) }}
                </el-tag>
                <span class="app-time">{{ app.updateTime }}</span>
              </div>
            </div>
            <div class="app-actions">
              <el-button-group>
                <el-button size="small" @click="handleEdit(app)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button size="small" @click="handlePreview(app)">
                  <el-icon><View /></el-icon>
                  预览
                </el-button>
                <el-dropdown @command="(cmd) => handleCommand(cmd, app)">
                  <el-button size="small">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="publish" v-if="app.status === 'development'">
                        <el-icon><Promotion /></el-icon>
                        发布
                      </el-dropdown-item>
                      <el-dropdown-item command="copy">
                        <el-icon><DocumentCopy /></el-icon>
                        复制
                      </el-dropdown-item>
                      <el-dropdown-item command="export">
                        <el-icon><Download /></el-icon>
                        导出
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-button-group>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[8, 16, 24, 32]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 创建应用对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建应用"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用图标" prop="icon">
          <el-select v-model="form.icon" placeholder="请选择图标">
            <el-option label="文件夹" value="Folder" />
            <el-option label="文档" value="Document" />
            <el-option label="数据分析" value="DataAnalysis" />
            <el-option label="购物车" value="ShoppingCart" />
            <el-option label="办公楼" value="OfficeBuilding" />
          </el-select>
        </el-form-item>
        <el-form-item label="应用描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入应用描述" />
        </el-form-item>
        <el-form-item label="创建方式" prop="createMethod">
          <el-radio-group v-model="form.createMethod">
            <el-radio value="blank">空白应用</el-radio>
            <el-radio value="template">从模板创建</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择模板" prop="templateId" v-if="form.createMethod === 'template'">
          <el-select v-model="form.templateId" placeholder="请选择模板">
            <el-option label="基础CRUD应用" value="1" />
            <el-option label="审批流应用" value="2" />
            <el-option label="数据报表应用" value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">创建</el-button>
      </template>
    </el-dialog>

    <!-- AI创建对话框 -->
    <el-dialog
      v-model="showAIDialog"
      title="AI创建应用"
      width="700px"
    >
      <el-alert
        title="描述你想要创建的应用，AI会自动生成完整的应用结构"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />
      <el-input
        v-model="aiInput"
        type="textarea"
        :rows="5"
        placeholder="例如：创建一个客户关系管理(CRM)系统，包含客户管理、销售机会、合同管理、数据报表等功能模块"
      />
      <template #footer>
        <el-button @click="showAIDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAICreate" :loading="aiCreating">
          <el-icon><MagicStick /></el-icon>
          AI生成
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  Plus, MagicStick, Edit, View, More, Promotion, DocumentCopy,
  Download, Delete, Folder, Document, DataAnalysis, ShoppingCart,
  OfficeBuilding
} from '@element-plus/icons-vue'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 应用列表
const applications = ref([
  {
    id: 1,
    name: '员工管理系统',
    description: '完整的员工信息管理、考勤、薪资等功能',
    icon: 'OfficeBuilding',
    status: 'published',
    updateTime: '2025-01-15',
    pages: 8,
    forms: 12
  },
  {
    id: 2,
    name: '采购管理',
    description: '采购申请、审批、订单管理一体化',
    icon: 'ShoppingCart',
    status: 'published',
    updateTime: '2025-01-10',
    pages: 6,
    forms: 8
  },
  {
    id: 3,
    name: '销售报表',
    description: '多维度销售数据分析和可视化展示',
    icon: 'DataAnalysis',
    status: 'development',
    updateTime: '2025-01-18',
    pages: 5,
    forms: 3
  },
  {
    id: 4,
    name: '文档管理',
    description: '企业文档存储、版本控制、权限管理',
    icon: 'Document',
    status: 'published',
    updateTime: '2025-01-12',
    pages: 7,
    forms: 5
  }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 8,
  total: 4
})

// 创建对话框
const showCreateDialog = ref(false)
const showAIDialog = ref(false)
const aiCreating = ref(false)
const aiInput = ref('')
const formRef = ref(null)

const form = reactive({
  name: '',
  icon: 'Folder',
  description: '',
  createMethod: 'blank',
  templateId: ''
})

const rules = {
  name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入应用描述', trigger: 'blur' }]
}

// 方法
const getStatusType = (status) => {
  const typeMap = {
    development: 'warning',
    published: 'success',
    disabled: 'danger'
  }
  return typeMap[status] || ''
}

const getStatusLabel = (status) => {
  const labelMap = {
    development: '开发中',
    published: '已发布',
    disabled: '已停用'
  }
  return labelMap[status] || status
}

const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}

const handleCreate = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('创建应用:', form)
      ElMessage.success('应用创建成功')
      showCreateDialog.value = false
    }
  })
}

const handleAICreate = async () => {
  if (!aiInput.value.trim()) {
    ElMessage.warning('请输入应用描述')
    return
  }

  aiCreating.value = true

  // 模拟AI创建
  setTimeout(() => {
    ElMessage.success('AI应用生成成功！正在跳转到编辑页面...')
    aiCreating.value = false
    showAIDialog.value = false
    aiInput.value = ''
    
    // 跳转到页面设计器
    setTimeout(() => {
      router.push('/lowcode/page-designer')
    }, 1000)
  }, 3000)
}

const handleEdit = (app) => {
  router.push({ path: '/lowcode/page-designer', query: { id: app.id } })
}

const handlePreview = (app) => {
  ElMessage.info('预览功能开发中')
}

const handleCommand = (command, app) => {
  switch (command) {
    case 'publish':
      ElMessageBox.confirm(`确定要发布应用 "${app.name}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        app.status = 'published'
        ElMessage.success('发布成功')
      })
      break
    case 'copy':
      ElMessage.success(`已复制应用 "${app.name}"`)
      break
    case 'export':
      ElMessage.success(`正在导出应用 "${app.name}"...`)
      break
    case 'delete':
      ElMessageBox.confirm(`确定要删除应用 "${app.name}" 吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success('删除成功')
      })
      break
  }
}
</script>

<style scoped>
.applications-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.app-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.app-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.3);
}

.app-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32px;
  margin-bottom: 15px;
}

.app-info h3 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
}

.app-desc {
  color: #909399;
  font-size: 14px;
  margin: 0 0 15px 0;
  min-height: 40px;
}

.app-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.app-time {
  color: #909399;
  font-size: 12px;
}

.app-actions {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>

